package com.time.toupdate.Controller;

import com.time.toupdate.utils.SendMailUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * Author:B
 * Description:      beifeng1212@qq.com    2647618100@qq.com
 */
@RestController
public class SendMail {
    @Resource
    private RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();

    @GetMapping("/getCode")
    @ResponseBody
    public String mail(@RequestParam("targetEmail") String targetEmail) {
        // 随机生成六位数验证码
        String authCode = String.valueOf(new Random().nextInt(899999) + 100000);
        SendMailUtil.sendEmailCode(targetEmail,authCode);
        return "ok";
    }
    @GetMapping("/getCode1")
    @ResponseBody
    public String mail1(@RequestParam("targetEmail") String targetEmail) {
        // 发送前先看下我们是否已经缓存了验证码
        String yzm = redisTemplate.opsForValue().get("yzm");
        // 判断是否存在
        if (yzm == null){
            // 生成六位数验证码
            int authNum = new Random().nextInt(899999) + 100000;
            String authCode = String.valueOf(authNum);
            // 不存在，我们发送邮箱给用户
            SendMailUtil.sendEmailCode(targetEmail, "你的验证码为:" + authCode + "(五分钟内有效)");
            // 存入redis中，设置有效期为1分钟
            redisTemplate.opsForValue().set("yzm", authCode, 1, TimeUnit.MINUTES);
            return "发送成功";
        }
        // 存在，直接返回，不再发送邮箱~
        return "请勿重复发送验证码";
    }
}